﻿using B.S.Meeting.Domain;
using B.S.Meeting.ErrorCode;
using B.S.Meeting.Infrastructure.Interfaces;
using B.S.Meeting.WriteAPI.Applications.Commands.Roles;
using MediatR;

namespace B.S.Meeting.WriteAPI.Applications.CommandHandlers.Roles
{
    public class UpdRoleCommandHandler : IRequestHandler<UpdRoleCommand, APIResult<int>>
    {
        private readonly IBaseRepository<Role> _rRep;
        private readonly ILogger<UpdRoleCommandHandler> _logger;

        public UpdRoleCommandHandler(IBaseRepository<Role> rRep, ILogger<UpdRoleCommandHandler> logger)
        {
            _rRep = rRep;
            _logger = logger;
        }

        public async Task<APIResult<int>> Handle(UpdRoleCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var role = await _rRep.GetByIdAsync(request.RoleId);
                if (role == null)
                {
                    _logger.LogWarning($"未找到ID为 {request.RoleId} 的角色");
                    return new APIResult<int>
                    {
                        Code = StatusEnumCode.Fail,
                        Message = "未找到指定的角色",
                        Data = 0
                    };
                }

                // 更新角色名称和部门描述
                role.RoleName = request.RoleName;
                role.DeptDesc = request.DeptDesc;

                var res = await _rRep.UpdAsync(role);
                _logger.LogInformation($"成功更新角色: ID {request.RoleId}, 名称: {request.RoleName},描述：{request.DeptDesc}");

                return new APIResult<int>
                {
                    Code = StatusEnumCode.Ok,
                    Message = "修改角色成功",
                    Data = res
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"修改角色时发生错误: ID {request?.RoleId}");
                return new APIResult<int>
                {
                    Code = StatusEnumCode.Fail,
                    Message = "修改角色失败",
                    Data = 0
                };
            }
        }
    }
}
